<template>
  <el-row :gutter="8">
    <el-col :xs="{span: 6}" :sm="{span: 6}" :md="{span: 6}" :lg="{span: 6}" :xl="{span: 6}" style="padding-right:8px;margin-bottom:30px;">
      <el-tree
        :data="treeData"
        :props="defaultProps"
        node-key="id"
        :default-expanded-keys="expandedkeys"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        @node-expand="handleNodeExpand"
        @node-collapse="handleNodeCollapse"
      />
    </el-col>
    <el-col :xs="{span: 18}" :sm="{span: 18}" :md="{span: 18}" :lg="{span: 18}" :xl="{span: 18}" style="padding-right:8px;margin-bottom:30px;">
      <el-table :data="detailData" border>
        <el-table-column label="参数" min-width="60">
          <template slot-scope="scope">
            {{ scope.row.key }}
          </template>
        </el-table-column>
        <el-table-column label="值" min-width="60" align="left">
          <template slot-scope="scope">
            {{ scope.row.value | numberFilter(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="说明" min-width="200" align="left">
          <template slot-scope="scope">
            {{ scope.row.desc }}
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
</template>

<script>
import { mapGetters } from 'vuex'
import { getZwmpChans, getZwmpChanDetail } from '@/api/resource'
import { Message } from 'element-ui'
import resize from '@/mixins/resize'
require('echarts/theme/macarons') // echarts theme
import { toThousandslsFilter, secondsFormat } from '@/utils/index.js'

export default {
  filters: {
    numberFilter(num, row) {
      if (row.key === '呼叫定时器' || row.key === 'sessionid' || row.key === 'handlerid' || row.key === '终端类型') {
        return num
      } else if (row.key === '呼叫建立时间') {
        return secondsFormat(num)
      } else if (row.key === '呼叫建立时间') {
        return secondsFormat(num)
      } else {
        return toThousandslsFilter(num)
      }
    }
  },
  mixins: [resize],
  props: {
    room: {
      type: String,
      require: true,
      default: ''
    },
    username: {
      type: String,
      require: true,
      default: ''
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '310px'
    }
  },
  data() {
    return {
      module: 0,
      timer: null,
      detailTimer: null,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      treeData: [],
      expandedkeys: [],
      detailData: []
    }
  },
  computed: {
    ...mapGetters(['name', 'roles'])
  },
  mounted() {
  },
  methods: {
    getChanTypeString(type) {
      const chanType = []
      chanType[15] = 'WebRTC音频通道'
      chanType[16] = 'WebRTC视频通道'
      chanType[17] = 'FFMPEG音频通道'
      chanType[18] = 'FFMPEG视频通道'
      return chanType[type]
    },
    getChanTypeValue(type) {
      const chanType = []
      chanType[15] = 1
      chanType[16] = 2
      chanType[17] = 1
      chanType[18] = 2
      return chanType[type]
    },
    getTermTypeString(type) {
      const termType = []
      termType[0] = '未知'
      termType[1] = 'WebRTC终端'
      termType[2] = '28181摄像头'
      termType[3] = 'SIP终端'
      termType[4] = '文件'
      return termType[type]
    },
    saveChanData(chans) {
      this.treeData = []
      const _this = this
      chans.forEach(function(confData, index, array) {
        const conf = { label: confData.confname, value: confData.confid, id: 'conf' + confData.confname, children: [] }
        confData.calls.forEach(function(callData, index, array) {
          const call = { label: callData.username, value: callData.callid, id: 'call' + callData.username, children: [] }
          callData.chans.forEach(function(chanData, index, array) {
            const chan = { label: _this.getChanTypeString(chanData.type) + ' [' + chanData.chanid + ']', id: 'chan' + chanData.chanid + chanData.type, value: chanData.chanid, type: chanData.type }
            call.children.push(chan)
          })
          conf.children.push(call)
        })
        _this.treeData.push(conf)
      })
    },
    handleNodeClick(item, node, array) {
      const _this = this
      if (item.id.substring(0, 4) === 'chan') { // 点击了chan
        _this.treeData.forEach(function(confData, index, array) {
          confData.children.forEach(function(callData, index, array) {
            callData.children.forEach(function(chanData, index, array) {
              if (chanData.id === item.id) {
                _this.getDetailData(_this.module, confData.value, callData.value, chanData.value, _this.getChanTypeValue(chanData.type))
              }
            })
          })
        })
      }
    },
    handleNodeExpand(item, node, array) {
      if (this.expandedkeys.indexOf(item.id) < 0) {
        this.expandedkeys.push(item.id)
      }
    },
    handleNodeCollapse(item, node, array) {
      const _this = this
      if (item.id.substring(0, 4) === 'conf') { // 从展开数组中删除子元素
        item.children.forEach(function(callData, index, array) {
          if (_this.expandedkeys.indexOf(callData.id) >= 0) { _this.expandedkeys.splice(_this.expandedkeys.indexOf(callData.id), 1) }
        })
      }
      if (_this.expandedkeys.indexOf(item.id) >= 0) { _this.expandedkeys.splice(_this.expandedkeys.indexOf(item.id), 1) }
    },
    getChanTree(module, room, username) {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      const _this = this
      _this.module = module
      _this.room = room
      _this.username = username
      getZwmpChans(module, room)
        .then((response) => {
          if (response.error_code === 200) {
            _this.saveChanData(response.data)
          }
        })
        .catch((error) => {
          Message.error(error)
        })
      this.timer = setInterval(() => {
        getZwmpChans(module, room)
          .then((response) => {
            if (response.error_code === 200) {
              _this.saveChanData(response.data)
            }
          })
          .catch((error) => {
            Message.error(error)
          })
      }, 1000)

      // 通过$once来监听定时器，在beforeDestroy钩子可以被清除。
      this.$once('hook:beforeDestroy', () => {
        console.log('清除定时器')
        clearInterval(this.timer)
      })
    },
    saveChanDetailData(data) {
      const detail = JSON.parse(data)
      this.detailData = []
      if (detail.videochan) {
        this.detailData.push({ 'key': '从通道接收包', 'value': detail.videochan['packetfromsdk'], 'desc': '从通道接收到的压缩帧', 'level': 0 })
        this.detailData.push({ 'key': '从通道接收帧', 'value': detail.videochan['framefromsdk'], 'desc': '从通道接收到的图像帧', 'level': 0 })
        this.detailData.push({ 'key': '向会议发送包', 'value': detail.videochan['packettoconf'], 'desc': '向会议发送的压缩帧', 'level': 0 })
        this.detailData.push({ 'key': '向会议发送帧', 'value': detail.videochan['frametoconf'], 'desc': '向会议发送的图像帧', 'level': 0 })
        this.detailData.push({ 'key': '从会议接收包', 'value': detail.videochan['packetfromconf'], 'desc': '从会议接收的压缩帧', 'level': 0 })
        this.detailData.push({ 'key': '从会议接收帧', 'value': detail.videochan['framefromconf'], 'desc': '从会议接收的图像帧', 'level': 0 })
        this.detailData.push({ 'key': '向通道发送包', 'value': detail.videochan['packettosdk'], 'desc': '向通道发送的压缩帧', 'level': 0 })
        this.detailData.push({ 'key': '向通道发送帧', 'value': detail.videochan['frametosdk'], 'desc': '向通道发送的图像帧', 'level': 0 })
      }
      if (detail.audiochan) {
        this.detailData.push({ 'key': '从通道接收包', 'value': detail.audiochan['totalfromsdk'], 'desc': '从通道接收音频包总次数', 'level': 0 })
        this.detailData.push({ 'key': '从通道接收包成功次数', 'value': detail.audiochan['succfromsdk'], 'desc': '从通道接收音频包成功次数', 'level': 0 })
        this.detailData.push({ 'key': '从通道接收包失败次数', 'value': detail.audiochan['failfromsdk'], 'desc': '从通道接收音频包失败次数', 'level': 0 })
        this.detailData.push({ 'key': '接收缓冲区成功次数', 'value': detail.audiochan['recvbufsucc'], 'desc': '通道接收缓冲区成功次数', 'level': 0 })
        this.detailData.push({ 'key': '接收缓冲区失败次数', 'value': detail.audiochan['recvbuffail'], 'desc': '通道接收缓冲区失败次数，接收的包尺寸不对', 'level': 0 })
        this.detailData.push({ 'key': '接收缓冲区满次数', 'value': detail.audiochan['recvbuffull'], 'desc': '通道接收缓冲区满次数', 'level': 0 })
        this.detailData.push({ 'key': '接收缓冲区总失败数', 'value': detail.audiochan['recvaudiofail'], 'desc': '通道接收缓冲区总失败次数', 'level': 0 })

        this.detailData.push({ 'key': '发送混音次数', 'value': detail.audiochan['sendmixfail'], 'desc': '接收缓冲送数据到混音模块错误次数', 'level': 0 })
        this.detailData.push({ 'key': '接收缓冲区空次数', 'value': detail.audiochan['sendmixfail'], 'desc': '接收缓冲无包次数', 'level': 0 })
        this.detailData.push({ 'key': '接收缓冲区读取正常次数', 'value': detail.audiochan['readrecvbufsucc'], 'desc': '接收缓冲读取正常次数', 'level': 0 })
        this.detailData.push({ 'key': '接收缓冲读取失败次数', 'value': detail.audiochan['readrecvbuffail'], 'desc': '接收缓冲读取失败次数', 'level': 0 })

        this.detailData.push({ 'key': '混音接收缓冲满次数', 'value': detail.audiochan['mixbuffull'], 'desc': '混音接收缓冲满次数', 'level': 0 })
        this.detailData.push({ 'key': '混音接收缓冲成功次数', 'value': detail.audiochan['mixbufsucc'], 'desc': '混音接收缓冲成功次数', 'level': 0 })

        this.detailData.push({ 'key': '混音接收缓冲区读取错误', 'value': detail.audiochan['readsendbuffail'], 'desc': '混音接收缓冲区读取错误', 'level': 0 })
        this.detailData.push({ 'key': '音频发送次数', 'value': detail.audiochan['sendsucc'], 'desc': '音频发送次数', 'level': 0 })
        this.detailData.push({ 'key': '音频发送失败次数', 'value': detail.audiochan['sendfail'], 'desc': '音频发送失败次数', 'level': 0 })
      }
      this.detailData.push({ 'key': '终端类型', 'value': this.getTermTypeString(detail['type']), 'desc': '终端类型', 'level': 0 })
      this.detailData.push({ 'key': 'sessionid', 'value': detail['sessionid'], 'desc': '', 'level': 0 })
      this.detailData.push({ 'key': 'handlerid', 'value': detail['handlerid'], 'desc': '', 'level': 0 })
      this.detailData.push({ 'key': '呼叫定时器', 'value': detail['calltimer'] === 0xffffffff ? '无效' : detail['calltimer'], 'desc': 'Call绑定的定时器超时时间', 'level': 0 })
    },
    getDetailData(module, conf, call, chan, type) {
      if (this.detailTimer) {
        clearInterval(this.detailTimer)
        this.detailTimer = null
      }
      const _this = this
      getZwmpChanDetail(module, conf, call, chan, type)
        .then((response) => {
          if (response.error_code === 200) {
            _this.saveChanDetailData(response.data.result)
          }
        })
        .catch((error) => {
          Message.error(error)
        })
      this.detailTimer = setInterval(() => {
        getZwmpChanDetail(module, conf, call, chan, type)
          .then((response) => {
            if (response.error_code === 200) {
              _this.saveChanDetailData(response.data.result)
            }
          })
          .catch((error) => {
            Message.error(error)
          })
      }, 1300)

      // 通过$once来监听定时器，在beforeDestroy钩子可以被清除。
      this.$once('hook:beforeDestroy', () => {
        console.log('清除定时器')
        clearInterval(this.detailTimer)
      })
    },
    clearTimer() {
      console.log('外部指定清除定时器')
      clearInterval(this.timer)
      clearInterval(this.detailTimer)
    }
  }
}
</script>

<style lang="scss" >
.el-table .warning-row {
      background: oldlace;
    }
.box-card-component {
  .el-card__header {
    padding: 0px !important;
  }
  .el-card__body {
    padding: 0px !important;
  }
}
</style>
<style lang="scss" scoped>

.box-card-component {
  .box-card-header {
    position: relative;
    height: 220px;
    img {
      width: 100%;
      height: 100%;
      transition: all 0.2s linear;
      &:hover {
        transform: scale(1.1, 1.1);
        filter: contrast(130%);
      }
    }
  }
  .card-panel-text {
    line-height: 18px;
    color: rgba(0, 0, 0, 0.55);
    font-size: medium;
    font-weight: bold;
    margin-top: 14px;
    margin-left: 14px;
  }
  .progress-item {
    margin-bottom: 10px;
    font-size: 14px;
  }
  .el-header,
  .el-footer {
    background-color: #b3c0d1;
    color: #333;
    text-align: center;
    line-height: 60px;
  }

  .el-aside {
    background-color: #d3dce6;
    color: #333;
    div {
      text-align: center;
      vertical-align: middle;
      display: table-cell;
      margin: auto;
    }
  }

  .el-main {
    background-color: #e9eef3;
    color: #333;
    text-align: center;
    vertical-align: middle;
    line-height: 40px;
  }

  body > .el-container {
    margin-bottom: 40px;
  }

  .el-container:nth-child(5) .el-aside,
  .el-container:nth-child(6) .el-aside {
    line-height: 260px;
  }

  .el-container:nth-child(7) .el-aside {
    line-height: 320px;
  }
  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
    text-align: center;
    vertical-align: middle;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
  @media only screen and (max-width: 1510px) {
    .mallki-text {
      display: none;
    }
  }
}
</style>
